package sharing

/**
 * 工具方法的service
 */
class Utils2Service {
    def utilsService
    /*
判断流程实体中摸个环节是否存在字段相同的实体,存在返回 存在实体的List
默认返回 null
参数:map.Domain  实体Class , map.id  实体id可以为空 ,map.zdName  实体字段名 ,map.zdValue 字段对应的值
*/

    def zdExitInLiuc(map) {
        if (!utilsService.validString(map.Domain)) throw new IllegalArgumentException("参数Domain有误")
        else if (!utilsService.validString(map.zdName)) throw new IllegalArgumentException("参数zdName有误")
        else if (!utilsService.validString(map.zdValue)) throw new IllegalArgumentException("参数zdValue有误")
        else if (!utilsService.validString(map.htName)) throw new IllegalArgumentException("参数 htName 有误")
        def Instance = map.Domain
        def result = utilsService.getHtAllPiid(map)
        if (utilsService.validString(map.id)) {
            result = result.findAll {
                it."${map.zdName}"?.toString() == map.zdValue?.toString() && it.id?.toString() != map.id?.toString()
            }
        } else {
            result = result.findAll { it."${map.zdName}"?.toString() == map.zdValue?.toString() }
        }
        //相同流程的 可以相同,对于驳回的适用
        if (utilsService.validString(map.piid)) result = result.findAll { it.piid?.toString() != map.piid?.toString() }
        if (result.size() == 0) result = null
        result
    }

    // 得到 项目启动的模式名称 如 DEVELOPMENT   PRODUCTION
    def getModelName() {
        grails.util.Environment.getCurrent().name.toUpperCase()
    }
    //把 map的List 中的key改为小写   ,主要用于:sql语句查出来的list中每个键默认大写 ,用于转换
    def changeMap(list) {
        def gList = []
        list.each { m ->
            def gListMap = [:]
            m.each { k, v ->
                gListMap.put(k.toString().toLowerCase(), v)
            }
            gList << gListMap
        }
        gList
    }
    /**
     * 获得ip地址
     * @param request
     * @return
     */
    String getIp(javax.servlet.http.HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

    String getUuid() {
        def uuid = UUID.randomUUID().toString()
        def ustr = uuid.toUpperCase()
        return ustr
    }
    /**
     *  编号 生成
     *  入参: InstanceProcess  流程实体 class , htName  需要自动编号的环节英文名  ,codeName  需要赋值编码的字段名称,piid  当前流程的piid  ,codePre  编号固定的前缀,codeLength 编号中顺序号的长度 为0 时表示不固定
     *  例如:  [InstanceProcess:FybxProcess,htName:'',codeName:'code',piid:'123',codePre:"YHMD-FY-${new Date().format('yyyy')}",codeLength:1]
     *  返回值: 完整的编号(包括前缀)
     */
    def buidCode(map) {
        def InstanceProcess = map.InstanceProcess //流程实体 class
        def htName = map.htName  // 需要自动编号的环节英文名
        def piid = map.piid  //当前流程的piid
        def codeName = map.codeName  //需要赋值编码的字段名称
        def codePre = map.codePre  //编号固定的前缀
        def codeLength = map.codeLength  //编号中顺序号的长度 为0 时表示不固定
        def oldCode = InstanceProcess.findByHtNameAndPiidAndCodeIsNotNull(htName, piid)?."${codeName}"
        def InstanceName = InstanceProcess.getSimpleName()
        def result = ""
        if (!oldCode) {
            def year = new Date().format('yyyy')
            def syg = InstanceProcess.findAll(" from ${InstanceName} where ${codeName} is not null and ${codeName} like '${codePre}%' order by ${codeName} desc ").find {
                true
            }
            def code = ''
            if (!syg) {
                if (codeLength != 0) {
                    code = String.format("%0${codeLength}d", 0)
                } else
                    code = codePre + '0'
            } else
                code = syg."${codeName}"
            if (code.size() >= (codePre.size() + 1)) {
                code = code.substring(codePre.size() + 1) ?: 0
            }
            code = (code as long)
            code = code + 1
            if (codeLength != 0) {
                code = String.format("%0${codeLength}d", code)
            }
            result = codePre + code?.toString()
        } else {
            result = oldCode
        }
        result
    }

    def openJsConfigList(params) {
        log.debug(params)
        InputStream fis;
        def fileName="openJsConfig.json"
        if (params.fileName) fileName=params.fileName
        def xmmc="prm"
        if (params.xmmc) xmmc=params.xmmc
        if (modelName == 'DEVELOPMENT') {
            fis = new FileInputStream("../${xmmc}/web-app/${fileName}");
        } else {
            def xmlu=utilsService.PATHMAP.get(xmmc)
            def path=utilsService.ROOT_PATH +xmlu+"/"+fileName
            log.debug(path)
            if(utilsService.ROOT_PATH.contains("web-app")){//开发工具 产品模式下的路径
                fis = new FileInputStream("../${xmmc}/web-app/${fileName}");
            }else{// tomcat 部署下的路径
                fis = new FileInputStream(path);
            }

        }
        String str = fis.getText("utf-8")
        def map = utilsService.parseJSON2Map(str)
        return map?.get('config')
    }
//    def saveOpenJsConfig(params){
//        def list = openJsConfigList(params)
//        list.each {
//            def map=[:]
//            map.type1=it.type1
//            map.typeLclx=it.typeLclx
//            map.type3=it.type3
//            map.xmmc = it.xmmc
//            map.address = it.address
//            map.fqActionUrl = it.fqActionUrl
//            map.description = it.description
//            map.controlerName = it.controlerName
//            map.jsXtype = it.jsXtype
//            if (map.address.toString().contains("/") && map.address.toString().contains(".js")) {
//                def a = map.address
//                map.jsName = a[a.lastIndexOf("/") + 1..a.lastIndexOf(".js") - 1]
//            }
//            map.address=utilsService.PATHMAP.get(map.xmmc)+map.address
//            map.lclx=Dict.findByCode(map.typeLclx)
//            map.forceUpdate=true
//            OpenJs openJs = OpenJs.findByJsNameAndXmmc( map.jsName, map.xmmc)
//            if (!openJs) {
//                openJs = new OpenJs(map)
//                if (!openJs.save(flush: true)){
//                    openJs.errors.each {
//                        log.error(it)
//                    }
//                }
//            } else {
//                if (map.forceUpdate) {
//                    openJs.properties = map
//                    if (!openJs.save(flush: true)){
//                        openJs.errors.each {
//                            log.error(it)
//                        }
//                    }
//                }
//            }
//        }
//    }
    def openJsConfigList() {
        InputStream fis;
        fis = new FileInputStream(utilsService.ROOT_PATH + "/openJsConfig.json");
        String str = fis.getText("utf-8")
        def map = utilsService.parseJSON2Map(str)
        return map?.get('config')
    }
    // 得到配置文件的mapList
    def configList(String node = 'config') {
        InputStream fis;
        if (modelName == 'DEVELOPMENT') {
            fis = new FileInputStream(utilsService.ROOT_PATH + "/config_dev.json");
        } else {
            fis = new FileInputStream(utilsService.ROOT_PATH + "/config.json");
        }
        String str = fis.getText("utf-8")
        def map = utilsService.parseJSON2Map(str)
        return map?.get(node)
    }
    // 配置的项目名称
    def getXmmcList() {
        return configList()?.xmmc
    }
    //获取配置中指定项目的信息
    def getXmxx(xmmc) {
        def xmList = configList()
        def resMap = [:]
        xmList.each {
            if (it.xmmc == xmmc) resMap = it
        }
        return resMap
    }


}
